<?php

// +----------------------------------------------------------------------
// 外部收文
// +----------------------------------------------------------------------

namespace app\document\controller;
error_reporting(0);
use app\document\service\DataService;
use library\Controller;
use think\Db;
use tool\office2pdf;
use app\document\model\Doc as DocX;



/**
 * 日常外部收文
 */
class Doc extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'Document';

    /**
     * 在办列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
    	#print_r(session('admin_user')['nickname']);
    	#
    	$allusers = session('admin_user')['nickname'];

        $this->title = '在办事项';
        $this->_query($this->table)->like('title,docunit,docno')
        	 ->where("allusers LIKE '%".$allusers."%' AND is_deleted=0 AND status=1 ")
        	 ->equal('status')->order(' status ASC , id DESC')->page();
    }



    /**
     * 代办列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function daiban()
    {
    	#print_r(session('admin_user')['nickname']);
    	#
    	$allusers = session('admin_user')['nickname'];

        $this->title = '待办事项';
        $this->_query($this->table)->like('title,docunit,docno')->field('D.id, D.title, D.docno,D.docunit,D.classes,D.jinji,D.create_at,D.status')
             ->alias('D')
			->join('flow F','D.id = F.docid')
        	 ->where("F.username LIKE '%".$allusers."%' AND D.is_deleted=0 AND D.status=1 AND F.status=1 AND F.info='' AND types!='shoufawenyuan' AND F.doctypes='doc' ")
        	 ->equal('D.status')->order(' D.status ASC , D.id DESC')->group('F.docid')->page();
/*
SELECT D.*
FROM `document` AS D
INNER JOIN `flow` AS F ON F.`docid`=d.`id`
WHERE F.`username` =(

SELECT nickname FROM system_user WHERE `id`='10001'

) and F.info ='' AND F.`status` =1

 */        
    }


    /**
     * 已办结
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function doc_done()
    {
    	#print_r(session('admin_user')['nickname']);
    	#
    	$allusers = session('admin_user')['nickname'];

        $this->title = '已完成';
        $this->_query($this->table)->like('title,docunit,docno')
        	 ->where("allusers LIKE '%".$allusers."%' AND is_deleted=0 AND status=2 ")
        	 ->equal('status')->order(' status ASC , id DESC')->page();
        $this->fetch();
    }


    protected function _page_filter(&$data){
        foreach ($data as &$vo) {
            $rs = Db::name('Flow')->field('*')->where(" username ='".session('admin_user.nickname')."' AND docid= '".$vo['id']."'  AND status =1 AND doctypes= 'doc' AND info='' ")->find();
            if($rs){

                $count =Db::name('Flow')->where("docid= '".$vo['id']."'  AND status =1 AND doctypes= 'doc' AND info='' AND flag< ".$rs['flag'])->count('id');
                if($count >=1){
                     $vo['flowcount'] = 0;
                }else{
                     $vo['flowcount'] = 1;
                }               
            }else{
                $vo['flowcount'] = 0;
            }
            
        }
        #print_r($rs);
    }

    //新增的时候插入流程
    private function Insertflow($data , $info , $types ,$ids , $flag ,$doctypes)
    {
        if($data ==''){
            return false;
        }
        $tmp1 = explode(',' , $data);
        $flow1 =[];
        if(is_array($tmp1)){
            foreach ($tmp1 as &$v) {
                if($v !=''){
                    array_push($flow1, [
                        'docid'     => $ids,
                        'username'  => $v,
                        'types'     => $types,
                        'info'      => $info,
                        'addtime'   => time(),
                        'files'     => '',
                        'flag'      => $flag,
                        'doctypes'  => $doctypes,
                    ]);
                }
            }
        }else{
            $flow1[] =[
                'docid'     => $ids,
                'username'  => $tmp1,
                'types'     => $types,
                'info'      => $info,
                'addtime'   => time(),
                'files'     => '',
                'flag'      => $flag,
                'doctypes'  => $doctypes,
            ];
        }
        if (!empty($flow1)) {
            Db::name('Flow')->insertAll($flow1);
        }
        return true;
    }

    /**
     * 添加
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
    	$this->title = '收文登记';



    	//print_r(session('admin_user'));
    	if ($this->request->isPost()) {

    		list($data1, $string) = [$this->request->post(), []];

            $data1['addtime'] =time();

            if($data1['docauthor'] ==''){
                $data1['docauthor'] =session('admin_user')['nickname'];
            }
            

    		$data1['allusers'] = $data1['docauthor'].','.$data1['doccharger'].','.$data1['docleader'].','.$data1['docread'].','.$data1['docdo'].','.session('admin_user')['nickname'];
			
			$data1['create_at'] = date('Y-m-d H:i:s', time());

    		$ids =Db::name('Document')->strict(false)->insertGetId($data1);

            //收文人发布
            if($data1['docauthor'] !=''){
                $this->Insertflow($data1['docauthor'] , $info ='收文完成' , $types='shouwen' , $ids  , $flag = 0 , 'doc');
            }

            //拟办人
            $this->Insertflow($data1['doccharger'] , $info ='' , $types='doccharger' , $ids , $flag = 1 , 'doc');

            //领导批示
            $this->Insertflow($data1['docleader'] , $info ='' , $types='docleader' , $ids , $flag = 2 , 'doc');

            //传阅
            $this->Insertflow($data1['docread'] , $info ='' , $types='docread' , $ids , $flag = 3 , 'doc');

            //办理
            $this->Insertflow($data1['docdo'] , $info ='' , $types='docdo' , $ids , $flag = 4 , 'doc');

            //回到收发文员那里
            $this->Insertflow(session('admin_user')['nickname'] , $info ='' , $types='shoufawenyuan' , $ids , $flag = 5 , 'doc');
            
    		//插入附件
        	list($post, $datas) = [$this->request->post(), []];
        	if (isset($post['fileurl']) && is_array($post['fileurl'])) {
        		$files =[];
                foreach (array_keys($post['fileurl']) as $key) {
                	array_push($files, [
	                    'docid'     => $ids,
	                    'username'    => $post['docauthor'],
	                    'original_name' => $post['original_name'][$key],
	                    'fileext'   => $post['fileext'][$key],
	                    'filesize'  => $post['filesize'][$key],
	                    'fileurl'   => $post['fileurl'][$key],
	                    'filename'  => $post['filename'][$key],
	                    'md5code'   => $post['md5code'][$key],
	                    'sha1code'  => $post['sha1code'][$key],
                        'flag'      => 'doc',
                	]);
                }
                if (!empty($files)) {
                    Db::name('Attachment')->insertAll($files);
                }
        	}

        	$this->success('恭喜, 数据保存成功!', '/admin.html#/document/doc/index.html?spm=m-62-63-64');
    	
    	}


    	$list = Db::name('SystemUser')->field('id,username,nickname')->where('id >10000')->where(['status'=>'1'])->select();
    	$str ='';
    	foreach ($list as &$value) {
    		$str .="{name:'".$value['nickname']."', value: '".$value['nickname']."'},\r\n";
    	}
    	$docleader ="";
    	$docread ="";
    	$docdo ="";
    	$docauthor =session('admin_user.nickname');
    	$this->assign('docauthor' , $docauthor);  	
    	$this->assign('docleader' , $docleader);  	
    	$this->assign('docread' , $docread);  	
    	$this->assign('docdo' , $docdo);  	
    	$this->assign('str' , $str);  	
        $this->_form($this->table, 'form');
    }


    /**
     * 修改
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {

        $this->title = '公文审批/流转';


        $nickname = session('admin_user')['nickname'];
        $user =Db::table('System_User')->where(['nickname'=>$nickname])->find();

        $pishi =explode("\r\n" , $user['pishi']);
        #print_r($pishi);
        #
        
        $signature_list =Db::table('Signature')->where(['nickname'=>$nickname])->select();


    	//print_r(session('admin_user')['nickname']);
    	$id =intval($this->request->param('id'));

    	$rs =Db::table('Document')->where('id',$id)->find();


    	$rs_flow = Db::table('Flow')
    			->where( "  username ='".session('admin_user.nickname')."' AND docid='".$rs['id']."' AND status=1 AND info ='' ")
    			->count('id');

    	$list_flow = Db::table('Flow')
    			->where( "  docid='".$rs['id']."' AND status=1 AND info !='' ")
    			->order('addtime ASC,id ASC')
    			->select();

    	if ($this->request->isPost()) {

    		if($rs['status'] ==2)
    		{
    			$this->error('该文件已经办结，无法再流转！' );
    		}


    		list($data1, $string) = [$this->request->post(), []];
	    	if (session('admin_user')['nickname'] !== $data1['docauthor'] ) {
	    		$this->error('权限不足，操作失败' );
	    	}
	    	
    		$data1['allusers'] = $data1['docauthor'].','.$data1['doccharger'].','.$data1['docleader'].','.$data1['docread'].','.$data1['docdo'].','.session('admin_user')['nickname'];
    		$data1['allusers'] =join(',' , array_unique(  explode(',' ,$data1['allusers']) ) ) ;


            //理情况处理
            $data1['docleader'] = $this->saveEdit($data1['docleader'] , $rs['docleader'] , $types='docleader' , $rs['id'] , 2, 'doc');
            $data1['docread'] = $this->saveEdit($data1['docread'] , $rs['docread']  , $types='docread' , $rs['id'] , 3, 'doc');
            $data1['docdo'] = $this->saveEdit($data1['docdo'] , $rs['docdo']  , $types='docdo' , $rs['id'] , 4, 'doc');

			Db::name('document')
			    ->where('id', $data1['id'])
			    ->strict(false)
			    ->data($data1)
			    ->update();


        	list($post, $datas) = [$this->request->post(), []];
        	if (isset($post['fileurl']) && is_array($post['fileurl'])) {
        		$files =[];
                foreach (array_keys($post['fileurl']) as $key) {
                	array_push($files, [
	                    'docid'     => $data1['id'],
	                    'username'    => $post['docauthor'],
	                    'original_name' => $post['original_name'][$key],
	                    'fileext'   => $post['fileext'][$key],
	                    'filesize'  => $post['filesize'][$key],
	                    'fileurl'   => $post['fileurl'][$key],
	                    'filename'  => $post['filename'][$key],
	                    'md5code'   => $post['md5code'][$key],
	                    'sha1code'  => $post['sha1code'][$key],
                        'flag'      => 'doc',
                	]);
                }
                if (!empty($files)) {
                    Db::name('Attachment')->insertAll($files);
                }
        	}

        	$this->success('恭喜, 数据保存成功!', '/admin.html#/document/doc/index.html?spm=m-62-63-64');
    	}


    	//------------------------------------------------------------


    	$files =Db::table('Attachment')->where(['docid'=>$id, 'flag'=>'doc'])->select();

        //显示批示人员
        $docleader =$this->showUser($rs['docleader']);

        $docread =$this->showUser($rs['docread']);

        $docdo =$this->showUser($rs['docdo']);

    	$list = Db::name('SystemUser')->field('id,username,nickname')->where('id >10000')->where(['status'=>'1'])->select();
    	$str ='';
    	foreach ($list as &$value) {
    		$str .="{name:'".$value['nickname']."', value: '".$value['nickname']."'},\r\n";
    	}

    	$this->assign('rs_flow' , $rs_flow);
    	$this->assign('id' , $id);
    	$this->assign('files' , $files);
    	$this->assign('str' , $str);
    	$this->assign('docdo' , $docdo);
    	$this->assign('docread' , $docread);
    	$this->assign('docleader' , $docleader);
    	$this->assign('docauthor' , $rs['docauthor']);
    	$this->assign('remark' , $rs['remark']);
    	$this->assign('list_flow' , $list_flow);
        $this->assign('pishi' , $pishi);
        $this->assign('signature_list' , $signature_list);
        $this->_form($this->table, 'form');
    }


    private function showUser($data)
    {
        if($data !=''){
            $tmp1 = explode(',' , $data);
            $str1 ='';
            if(is_array($tmp1)){
                foreach ($tmp1 as $key => &$v) {
                    $str1 .="'".$v."',";
                }

            }else{
                $str1 =$data;
            }
            $str1 =rtrim($str1 , ',');
        }
        return $str1;
    }


    private function saveEdit($data1 , $data2 , $types , $ids , $flag , $doctypes)
    {
            $data1_tmp =$data1; //表单提交的数据
            if($data1_tmp ==''){
                return false;
            }
            $array1 =explode(',' ,$data1_tmp);

            if($data2 !='' ){
                $this->delflow($data2 , $types , $ids);  //软删除
            }

            $tmp_leader =join(',' , array_unique(  $array1 ) ) ; //去重重组

            $tmp1 = explode(',' , $tmp_leader);
            $flow1 =[];
            if( count($tmp1) >= 1 ){
                foreach ($tmp1 as &$v) {
                    $tmp_count = Db::table('Flow')->where( ['username' => $v , 'types'=>$types ,'docid'=>$ids ])->count('id');
                    if($tmp_count ==1){
                        Db::table('Flow')->where("  username ='".$v."' AND types='".$types."' AND docid= '".$ids."'  ")->update(['status'=>'1']);
                    }
                    if($v !='' && $tmp_count ==0 ){
                        array_push($flow1, [
                            'docid'     => $ids,
                            'username'  => $v,
                            'types'     => $types,
                            'info'      => '',
                            'addtime'   => time(),
                            'files'     => '',
                            'flag'      => $flag,
                            'doctypes'  => $doctypes,
                        ]);
                    }
                }
            }
            if (!empty($flow1)) {
                Db::name('Flow')->insertAll($flow1);
            }
            return $data1_tmp;
    }




    public function delflow($data , $flag , $docid )
    {
    	$tmp1 = explode(',' , $data);
    	if(is_array($tmp1)){
    		foreach ($tmp1 as $key => $v) {
    			Db::table('Flow')->where("  username ='".$v."' AND types='".$flag."' AND docid='".$docid."' ")->update(['status'=>'0']);
    		}
    	}else{
    		Db::table('Flow')->where(" username ='".$tmp1."' AND types='".$flag."' AND docid='".$docid."' ")->delete(['status'=>'0']);
    	}
    }



    /**
     * 更改状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
    	
        $id =($this->request->param('id'));
        $ids =explode(',' , $id);

        if(count($ids) > 1){
            $this->error('强制办结，只能一次选择一条记录！' );
        }

    	$rs =Db::table('Document')->where([  'id'=>intval($id)  ])->find();
        if ($rs['status'] ==2) {
            $this->error('该记录已经办结或撤销，无法再强制办结！' );
        }

    	if($rs['docauthor'] !=session('admin_user')['nickname']){
    		$this->error('此文件无法强制办结!');
    	}

        $this->_save($this->table, ['status' => input('status', '2')]);
    }

    /**
     * 强制办结
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }


    /**
     * 文档打印
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function printdoc()
    {
    	$id =intval($this->request->param('id'));

    	$rs =Db::table('Document')->where(['id'=>$id , 'status'=>2])->find();


    	if(!$rs)
    	{
    		$this->error('文档不存在!');
    	}

        if (stripos($rs['allusers'], session('admin_user')['nickname'] ) ===FALSE) {
            $this->error('权限不足，操作失败！' ,'/admin.html');
        }

    	$file_list =Db::table('Attachment')
    			->where( "  docid='".$rs['id']."' AND flag='doc' ")
    			->select();
    	$flow_list = Db::table('Flow')->alias('a')->field('a.* , b.signatureurl')
                ->join('system_user b','b.nickname=a.username')
    			->where( "  a.docid='".$rs['id']."' AND a.status=1 AND a.info<>'' ")
    			->select();
        //print_r($flow_list);

    	$this->assign('rs' , $rs);
    	$this->assign('file_list' , $file_list);
    	$this->assign('flow_list' , $flow_list);


    	$this->fetch();
    }

    /**
     * 批示文件
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function saveinfo()
    {
    	if ($this->request->isPost()) {
    		$data =$this->request->param();
    		$rs['info'] = $data['info'];
    		$rs['docid'] = $data['docid'];
    		$rs['username'] = session('admin_user.nickname');

            $rs['files'] =$data['signature'];

            $data = Db::table('Document')
                ->where( "  id='".$rs['docid']."' ")
                ->find();

            if($data['status'] ==2)
            {
                $res =[];
                $res['code']  ='0';
                $res['status']  ='error';
                $res['msg']  ='文件已经办结，无法再审批！';
                return $res;
            }

    		Db::table('Flow')->where("  username ='".$rs['username']."' AND docid='".$rs['docid']."' AND status=1 AND info ='' ")
    		->update(['info'=>$rs['info'], 'addtime'=>time(), 'files'=>$rs['files'] ]);

    		$rs_flow = Db::table('Flow')
    			->where( "  docid='".$rs['docid']."' AND status=1 AND info ='' ")
    			->count('id');
    		if($rs_flow ==0){
    			Db::table('Document')->where("  id='".$rs['docid']."'  ")->update( ['status'=>2 ]);
    		}


    		$res =[];
    		$res['code']  ='1';
    		$res['status']  ='success';
    		$res['msg']  ='保存成功！';
    		return $res;
    	}
    }



    public function upload()
    {
        if($this->request->file('file')){
            $file       = $this->uploadfile('file','' ,[] , session('admin_user')['id']);
            if ($file) {
                echo json_encode($file);
            } else {
                echo json_encode($file);
            }
        }
    }


    public function uploadfile($name, $path = '', $validate = [], $user_id = 0)
    {
        $config = config('attchment');
        $file   = request()->file($name);
        if ($file) {
            $file_path = $config['path'] . $path;
            $file_url  = $config['url'] . $path;
            $validate  = array_merge($config['validate'], $validate);
            $info      = $file->validate($validate)->move($file_path);
            if ($info) {
                $file_info = [
                	'code'          => 0 ,
                    'user_id'       => $user_id,
                    'original_name' => $info->getInfo('name'),
                    'save_name'     => $info->getFilename(),
                    'save_path'     => str_replace("\\", "/",$file_path . $info->getSaveName()),
                    'extension'     => $info->getExtension(),
                    'mime'          => $info->getInfo('type'),
                    'size'          => $info->getSize(),
                    'md5'           => $info->hash('md5'),
                    'sha1'          => $info->hash(),
                    'url'           => str_replace("\\", "/",$file_url . $info->getSaveName())
                ];
                return $file_info;
            } else {
                return $file->getError();
            }
        } else {
            return '无法获取文件';
        }
        return false;
    }

    public function zipfile()
    {
        if ($this->request->isGet()) {
            $data =$this->request->param();
            $id =intval($data['id']);

            if($id <= 0){
                $res =[];
                $res['code'] =201;
                $res['msg'] ='参数错误!' ;

                echo json_encode($res); 
                die();
            }

            $file_list =Db::table('Attachment')
            ->where( "  docid='".$data['id']."' AND flag='doc' ")
            ->select();
            if( count($file_list) == 0){
                $res =[];
                $res['code'] =202;
                $res['msg'] ='文件列表为空!' ;

                echo json_encode($res); 
                die();
            }

            $res =[];
            $res['code'] =200;
            $res['msg'] ='成功!' ;
            $path =dirname( $file_list['0']['fileurl']);
            $res['data'] = $path;
            $res['files'] = $file_list;
           

            $outputFilename =str_replace("\\","/", ROOTPATH . $path .'/Doc_'.$id.'.zip' ); //ROOTPATH . $path .'/Doc_'.$id.'.zip';
            $res['outputFilename'] = $outputFilename;
            if(file_exists($outputFilename)){
                @unlink($outputFilename);
            }
            //echo json_encode($res);
            //    die();   
            $zipFile = new \PhpZip\ZipFile();
            try{
                $zipFile = new \PhpZip\ZipFile();
                foreach ($file_list as $v) {
                    $zipFile->addFile(ROOTPATH.$v['fileurl']);
                }
                $zipFile->saveAsFile($outputFilename); // save the archive to a file
                $zipFile->close(); // close archive  

            }
            catch(\PhpZip\Exception\ZipException $e){
                $res =[];
                $res['code'] =203;
                $res['msg'] ='发生未知错误，请联系管理员!' ;
                echo json_encode($res);
                die();                 
            }
            finally{
                $zipFile->close();
            }

            $res['down']  =$path .'/Doc_'.$id.'.zip';

            echo json_encode($res);
            die(); 
        }
    } 

    public function changepdf()
    {
        if ($this->request->isPost()) {
            $data =$this->request->param();
            $url = $data['url'];
            $ext = $data['ext'];
            $input =ROOTPATH . $url;
            $input = str_replace("\\","/",$input);
            $output = str_replace($ext,"pdf",$input);
			
			
			if(!file_exists($input)) {
				//echo "File : $input not found!";
				$res =[];
				$res['code'] =201;
				$res['msg'] ="File : $input not found!" ;

				echo json_encode($res); 
				exit;
			}

			$doc_arr = array('doc', 'docx', 'wps');
			$xls_arr = array('xls', 'xlsx', 'et');
			$ppt_arr = array('ppt', 'pptx', 'dps');

			if(in_array($ext, $doc_arr)) {
			  $wps = new \COM("Word.Application") or die('Com Error');

			  $doc = $wps->Documents->Open( $input );
			  $doc->ExportAsFixedFormat($output, 17);//17=pdf

			}elseif(in_array($ext, $xls_arr)) {
			  $wps = new \COM("Excel.Application") or die('Com Error');
			  
			  $doc = $wps->Workbooks->Open($input);
			  $doc->ExportAsFixedFormat(0, $output);//0=pdf
			}elseif(in_array($ext, $ppt_arr)) {
			  $wps = new \COM("Powerpoint.Application") or die('Com Error');
			  
			  $doc = $wps->Presentations->Open($input, true);
			  //$doc->ExportAsFixedFormat($output, 2);
			  $doc->SaveAs($output, 32, 1);//ppt另存为可以生成pdf
			}else{
			  echo "Src File Extension: $ext, is error";
			  exit;
			}
			$doc->Close();
			$wps->Quit();
			unset( $doc , $wps );
			
			//$pdf = new office2pdf();
			//$pdf->run($input,$output);
			
			
            //D:/phpStudy_64/WWW/www.3d95.net/ThinkAdmin-5/public/uploads/attachment/20191228/43ca1b27f4be484d5e7fbe13c9c72707.doc
            //$command = "java -jar ".ROOTPATH."/jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar ".$input."  " .$output;
            //exec($command, $output1);
			
            if(file_exists($output)) {
                $res =[];
                $res['code'] =200;
                $res['msg'] ='转换成功';

                echo json_encode($res);
            }else{
                $res =[];
                $res['code'] =201;
                $res['msg'] ='转换失败' . $command;

                echo json_encode($res); 
            }

        }
    }
}
